package com.rpc.example.spring.service;

import com.rpc.example.core.Request;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Elvis
 * @version 1.0, 2022/11/17
 */
@Slf4j
public class Median {

    public static final Map<String, BeanMethod> methodMap = new ConcurrentHashMap<>();
    public static final Map<String, Map<String, BeanMethod> > applicaitonNameMap = new ConcurrentHashMap<>();

    private static Median instance;

    private Median() {
    }

    public static Median getInstance() {
        if (instance == null) {
            synchronized (Median.class) {
                if (instance == null) {
                    instance = new Median();
                }
            }
        }
        return instance;
    }

    public Object invoke(Request request) throws InvocationTargetException, IllegalAccessException {
        String className = request.getClassName();
        String methodName = request.getMethodName();
        Map<String, BeanMethod> stringBeanMethodMap = applicaitonNameMap.get(request.getApplicationName());
        BeanMethod beanMethod = stringBeanMethodMap.get(className + "." + methodName);
        if (beanMethod == null) {
            log.warn("not found method in rpc service : {}.{}", className, methodName);
            return null;
        }
        return beanMethod.getMethod().invoke(beanMethod.getBean(), request.getParams());
    }
}
